package org.example.array;

import java.util.Arrays;
import java.util.stream.Collectors;

public class Solution88 {

    public static void main(String[] args) {
        int[] nums1 = { 1, 2, 3, 0, 0, 0 };
        int[] nums2 = { 2, 5, 6 };
        merge(nums1, 3, nums2, 3);
        // [1,2,2,3,5,6]
        System.out.println(getArrayString(nums1));

        int[] nums3 = { 1 };
        int[] nums4 = {};
        merge(nums3, 1, nums4, 0);
        // [1]
        System.out.println(getArrayString(nums3));

        int[] nums5 = { 0 };
        int[] nums6 = { 1 };
        merge(nums5, 0, nums6, 1);
        // [1]
        System.out.println(getArrayString(nums5));

        int[] nums7 = { 2, 0 };
        int[] nums8 = { 1 };
        merge(nums7, 1, nums8, 1);
        // [1]
        System.out.println(getArrayString(nums7));
    }

    public static void merge(int[] nums1, int m, int[] nums2, int n) {
        if (n == 0) {
            return;
        }
        if (m == 0) {
          for (int index = 0; index < nums1.length; index++) {
                nums1[index] = nums2[index];
          }
            return;
        }

        for (int i = m; i < m + n; i++) {
            nums1[i] = nums2[i - m];
        }
        System.out.println(nums1.toString());
        if (m + n <= 1) {
            return;
        }

        // 修改为冒牌排序法
        int i = m + n - 1;
        int j = m + n - 2;
        while (j >= 0) {
            if (nums1[i] < nums1[j]) {
                int value = nums1[j];
                nums1[j] = nums1[i];
                nums1[i] = value;
            }
            i--;
            j--;
        }
    }

    public static String getArrayString(int[] nums1) {
        return Arrays.stream(nums1).mapToObj(String::valueOf).collect(Collectors.joining(","));
    }
}
